package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.*;
import com.heima.article.entity.*;
import com.heima.article.feign.ApBehaviorEntryFeign;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.service.IApAuthorService;
import com.heima.article.service.IApCollectionService;
import com.heima.article.task.ArticleTask;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-14
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    IApArticleContentService apArticleContentService;

    @Autowired
    private ApBehaviorEntryFeign apBehaviorEntryFeign;

    @Autowired
    private IApAuthorService apAuthorService;

    @Autowired
    private IApArticleService apArticleService;

    /*@Autowired
    private ApBehaviorFeign apBehaviorFeign;*/

    @Autowired
    private IApCollectionService collectionService;

    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        // 需求分析
        // 判断是否包含文章id,有id的话需要更新文章
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto, article);
        if (dto.getId() == null) {
            // 保存文章
            this.save(article);
            // 保存文章内容
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(article.getId());
            content.setContent(dto.getContent());
            contentService.save(content);

            // 自动生成静态页  通过异步的方式来操作
            System.out.println(Thread.currentThread().getName() + "开始调用异步文章静态页生成...");
            articleTask.createHtml(article, dto.getContent());

            return ResponseResult.okResult(article.getId());
        } else {
            // 更新文章
            this.updateById(article);
            // 更新文章内容
            LambdaUpdateWrapper<ApArticleContent> update = new LambdaUpdateWrapper<>();
            update.eq(ApArticleContent::getArticleId, dto.getId());
            update.set(ApArticleContent::getContent, dto.getContent());
            contentService.update(update);
            return ResponseResult.okResult(dto.getId());
        }
    }

    @Autowired
    @Lazy
    private ArticleTask articleTask;

    /**
     * 加载文章列表
     *
     * @param dto
     * @param type 0:最新文章  1:更多文章
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, int type) {
        // 构建查询条件
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
        // 如果频道id不为空且不为0,添加频道条件
        if (dto.getChannelId() != null && dto.getChannelId() != 0) {
            query.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        if (type == 0) {
            // 加载最新,查询比页面传递的最大时间更新的数据
            query.gt(ApArticle::getPublishTime, dto.getMaxTime());
        } else {
            query.lt(ApArticle::getPublishTime, dto.getMinTime());
        }
        // 过滤已下架\已删除的文章
        query.eq(ApArticle::getIsDown, false);
        query.eq(ApArticle::getIsDelete, false);
        // 排序,按照发布时间倒序
        query.orderByDesc(ApArticle::getPublishTime);
        // 构建分页条件
        IPage<ApArticle> page = new Page<>(1, dto.getSize());
        // 执行分页查询
        IPage<ApArticle> iPage = this.page(page, query);
        // 返回通用响应
        return ResponseResult.okResult(iPage.getRecords());
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        // 根据id查询文章
        ApArticle article = this.getById(dto.getArticleId());
        // 根据文章id查询文章内容
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent content = contentService.getOne(query);
        // 构建响应
        Map<String, Object> map = new HashMap<>();
        map.put("config", article);
        map.put("content", content);
        return ResponseResult.okResult(map);
    }

    //文章数据回显
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //1.获取用户
        User user = AppThreadLocalUtil.get();

        Map<String, Object> map = new HashMap<>();
        //3.用户id不为空的情况
        if (user != null) {
            //3.1 封装用户id和类型type
            EntryAndTypeDto entryAndTypeDto = new EntryAndTypeDto();

            entryAndTypeDto.setEntryId(user.getUserId().toString());

            entryAndTypeDto.setType(1);
            //3.2 feign调用接口获取行为实体数据
            ApBehaviorEntry entry = apBehaviorEntryFeign.findEntry(entryAndTypeDto);
            //3.3 封装实体id和文章id
            EntryArticleDto entryArticleDto = new EntryArticleDto();

            // System.out.println("实体id" + entry.getId());

            entryArticleDto.setArticleId(dto.getArticleId());

            entryArticleDto.setEntryId(entry.getId().longValue());
            //3.4 feign调用点赞接口，获取点赞数据
            ApLikesBehavior isLike = apBehaviorEntryFeign.getIsLike(entryArticleDto);

            if (isLike.getArticleId() == null && isLike.getEntryId() == null) {
                //3.4.1 封装点赞数据
                map.put("islike", false);
            } else {
                //3.4.2 封装不喜欢数据
                System.out.println(isLike.getOperation());

                boolean isLike1 = isLike.getOperation() == 0 ? true : false;

                map.put("islike", isLike1);
            }
            //3.4 feign调用不喜欢接口，获取数据
            ApUnlikesBehavior unLike = apBehaviorEntryFeign.getUnLike(entryArticleDto);

            if (unLike.getArticleId() == null && unLike.getEntryId() == null) {
                //3.4.1 封装不喜欢数据
                map.put("isunlike", false);
            } else {

                boolean unLike1 = unLike.getType() == 0 ? true : false;
                //3.4.2 封装不喜欢数据
                map.put("isunlike", unLike1);
            }
            //3.4.1 获取文章所属用户id，为调用关注行为数据做准备
            ApArticle byId = apArticleService.getById(dto.getArticleId());

            LambdaQueryWrapper<ApAuthor> query2 = new LambdaQueryWrapper<>();

            query2.eq(ApAuthor::getId, byId.getAuthorId());

            ApAuthor one1 = apAuthorService.getOne(query2);

            Integer authorUserId = one1.getUserId();

            entryArticleDto.setArticleId(authorUserId.longValue());
            //3.4 feign调用关注接口接口，获取关注数据
            ApFollowBehavior isFollow = apBehaviorEntryFeign.getIsFollow(entryArticleDto);

            if (isFollow.getEntryId() == null && isFollow.getFollowId() == null) {
                //3.4.1 封装关注数据
                map.put("isfollow", false);
            } else {

                boolean isFollow1 = isFollow.getOperation() == 0 ? true : false;
                //3.4.2 封装关注数据
                map.put("isfollow", isFollow1);
            }
            //3.5 获取收藏行为数据
            LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();

            query.eq(ApCollection::getArticleId, dto.getArticleId()).eq(ApCollection::getEntryId, entry.getId());

            ApCollection one = collectionService.getOne(query);

            System.out.println(one);

            if (one == null) {
                //3.5.1 封装收藏数据
                map.put("iscollection", false);
            } else {
                //3.5.2 封装收藏数据
                map.put("iscollection", true);
            }
            return ResponseResult.okResult(map);
        }
        //4 设备id不为空
        if (dto.getEquipmentId() != null) {

            long equipmentId = Long.parseLong(dto.getEquipmentId());
            //4.1 封装设备id和类型type
            EntryAndTypeDto entryAndTypeDto = new EntryAndTypeDto();

            entryAndTypeDto.setEntryId(dto.getEquipmentId());

            entryAndTypeDto.setType(0);
            //4.2 feign调用接口获取行为实体数据
            ApBehaviorEntry entry = apBehaviorEntryFeign.findEntry(entryAndTypeDto);
            //4.3 封装实体id和文章id
            EntryArticleDto entryArticleDto = new EntryArticleDto();

            entryArticleDto.setArticleId(dto.getArticleId());

            entryArticleDto.setEntryId(entry.getId().longValue());
            //4.4 feign调用点赞接口，获取点赞数据
            ApLikesBehavior isLike = apBehaviorEntryFeign.getIsLike(entryArticleDto);

            if (isLike.getArticleId() == null && isLike.getEntryId() == null) {
                //4.3.1 封装点赞数据
                map.put("islike", false);
            } else {

                boolean isLike1 = isLike.getOperation() == 0 ? true : false;
                //4.3.2 封装点赞数据
                map.put("islike", isLike1);
            }
            //4.4 feign调用不喜欢接口，获取不喜欢数据
            ApUnlikesBehavior unLike = apBehaviorEntryFeign.getUnLike(entryArticleDto);

            if (unLike.getEntryId() == null && unLike.getArticleId() == null) {
                //4.4.1 封装不喜欢数据
                map.put("isunlike", false);
            } else {

                boolean unLike1 = unLike.getType() == 0 ? true : false;
                //4.4.2 封装不喜欢数据
                map.put("isunlike", unLike1);
            }

            //4.5.1 获取文章所属用户id，将用户id设置给entryArticleDto.setArticleId
            ApArticle byId = apArticleService.getById(dto.getArticleId());

            LambdaQueryWrapper<ApAuthor> query2 = new LambdaQueryWrapper<>();

            query2.eq(ApAuthor::getId, byId.getAuthorId());

            ApAuthor one1 = apAuthorService.getOne(query2);

            Integer authorUserId = one1.getUserId();

            entryArticleDto.setArticleId(authorUserId.longValue());
            //4.5.2 feign调用关注接口，获取关注数据
            ApFollowBehavior isFollow = apBehaviorEntryFeign.getIsFollow(entryArticleDto);

            if (isFollow.getFollowId() == null&& isFollow.getEntryId() == null) {
                //4.5.2.1 封装关注数据
                map.put("isfollow", false);
            } else {

                boolean isFollow1 = isFollow.getOperation() == 0 ? true : false;

                map.put("isfollow", isFollow1);
            }
            //4.6 获取收藏数据
            LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();

            query.eq(ApCollection::getArticleId, dto.getArticleId()).eq(ApCollection::getEntryId, entry.getId());

            ApCollection one = collectionService.getOne(query);

            if (one == null) {
                //4.6.1 封装收藏数据
                map.put("iscollection", false);
            } else {
                //4.6.1 封装收藏数据
                map.put("iscollection", true);
            }
        }
        return ResponseResult.okResult(map);
    }
}
